#include "amp_m4.h"
#include "stm32mp1xx.h"

#include "elog.h"
#include "charge_mem_tab.h"
#include "cmd_map_rw.h"

VIRT_UART_HandleTypeDef huart0;
uint8_t Copy_Buffer[MAX_BUFFER_SIZE];
uint8_t BuffTx[MAX_BUFFER_SIZE];
uint16_t RxSize = 0;
__IO FlagStatus flag = RESET;
__IO FlagStatus flagsend = RESET;
cmd_mode_te cmdworkmode;
sys_mode_te sysworkmode;
uint8_t databuff[50], Revdata[50];                                   // Revdata核间通讯接收数组  databuff核间通讯发送数组
uint8_t messagedata[50] = {0x12, 0x00, 29, 10, 1, 1, 0, 0, 2, 0, 0}; // M核传递数据中间数组
uint8_t num = 0, RECIVE_ACK = 0, ACKFLAG = 0, Ttickack = 0;

QueueHandle_t send_q;

// base64表，用于编码
//  base64 转换表, 共64个
static const char base64_alphabet[] = {
    'A', 'B', 'C', 'D', 'E', 'F', 'G',
    'H', 'I', 'J', 'K', 'L', 'M', 'N',
    'O', 'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g',
    'h', 'i', 'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    '+', '/'};

// 解码时使用
static const unsigned char base64_suffix_map[256] = {
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 255,
    255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 253, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
    255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6,
    7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255,
    255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
    37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
    49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255};
static uint8_t codelen[200] = {8, 0, 0, 0, 1, 1, 4, 0, 0, 0, 4, 0, 0, 0, 1, 1, 1, 4, 0, 0, 0, 2, 0, 2, 0, 1, 1, 2, 0, 9, 0, 0, 0, 0};
static char cmove_bits(unsigned char src, unsigned lnum, unsigned rnum)
{
    src <<= lnum; // src = src << lnum;
    src >>= rnum; // src = src >> rnum;
    return src;
}

// 编码过程，其中in待编码字符，out为编码后字符
int base64_encode(char *indata, int inlen, char *outdata, int *outlen)
{

    int ret = 0; // return value
    if (indata == NULL || inlen == 0)
    {
        return ret = -1;
    }

    int in_len = 0;  // 源字符串长度, 如果in_len不是3的倍数, 那么需要补成3的倍数
    int pad_num = 0; // 需要补齐的字符个数, 这样只有2, 1, 0(0的话不需要拼接, )
    if (inlen % 3 != 0)
    {
        pad_num = 3 - inlen % 3;
    }
    in_len = inlen + pad_num; // 拼接后的长度, 实际编码需要的长度(3的倍数)

    int out_len = in_len * 8 / 6; // 编码后的长度

    char *p = outdata; // 定义指针指向传出data的首地址

    // 编码, 长度为调整后的长度, 3字节一组
    for (int i = 0; i < in_len; i += 3)
    {
        int value = *indata >> 2;        // 将indata第一个字符向右移动2bit(丢弃2bit)
        char c = base64_alphabet[value]; // 对应base64转换表的字符
        *p = c;                          // 将对应字符(编码后字符)赋值给outdata第一字节

        // 处理最后一组(最后3字节)的数据
        if (i == inlen + pad_num - 3 && pad_num != 0)
        {
            if (pad_num == 1)
            {
                *(p + 1) = base64_alphabet[(int)(cmove_bits(*indata, 6, 2) + cmove_bits(*(indata + 1), 0, 4))];
                *(p + 2) = base64_alphabet[(int)cmove_bits(*(indata + 1), 4, 2)];
                *(p + 3) = '=';
            }
            else if (pad_num == 2)
            { // 编码后的数据要补两个 '='
                *(p + 1) = base64_alphabet[(int)cmove_bits(*indata, 6, 2)];
                *(p + 2) = '=';
                *(p + 3) = '=';
            }
        }
        else
        { // 处理正常的3字节的数据
            *(p + 1) = base64_alphabet[cmove_bits(*indata, 6, 2) + cmove_bits(*(indata + 1), 0, 4)];
            *(p + 2) = base64_alphabet[cmove_bits(*(indata + 1), 4, 2) + cmove_bits(*(indata + 2), 0, 6)];
            *(p + 3) = base64_alphabet[*(indata + 2) & 0x3f];
        }

        p += 4;
        indata += 3;
    }

    if (outlen != NULL)
    {
        *outlen = out_len;
    }

    return ret;
}

// 解码函数，in为代解码字符，out为解码后的字符
int base64_decode(char *indata, int inlen, char *outdata, int *outlen)
{
    int ret = 0;
    if (indata == NULL || inlen <= 0 || outdata == NULL || outlen == NULL)
    {
        return ret = -1;
    }
    if (inlen % 4 != 0)
    { // 需要解码的数据不是4字节倍数
        return ret = -2;
    }

    int t = 0, x = 0, y = 0, i = 0;
    unsigned char c = 0;
    int g = 3;

    while (indata[x] != 0)
    {
        // 需要解码的数据对应的ASCII值对应base64_suffix_map的值
        unsigned char intda = indata[x++];
        c = base64_suffix_map[intda];
        if (c == 255)
            return -1; // 对应的值不在转码表中
        if (c == 253)
            continue; // 对应的值是换行或者回车
        if (c == 254)
        {
            c = 0;
            g--;
        }                 // 对应的值是'='
        t = (t << 6) | c; // 将其依次放入一个int型中占3字节
        if (++y == 4)
        {
            outdata[i++] = (unsigned char)((t >> 16) & 0xff);
            if (g > 1)
                outdata[i++] = (unsigned char)((t >> 8) & 0xff);
            if (g > 2)
                outdata[i++] = (unsigned char)(t & 0xff);
            y = t = 0;
        }
    }
    if (outlen != NULL)
    {
        *outlen = i;
    }
    return ret;
}

/**
 * @brief M4打包发送数据到A7
 */
void sendmesg(void)
{
    int sendlen = 0;
    int inlen = 0;
    char senddata[100] = {0};
    uint8_t i = 0;
    uint8_t TESTDATA[50] = "test 123";
    static uint32_t Ttick = 0;
    static uint8_t sendcount = 0; //,virtsendlen=0
    static amp_send_msg_t amp_send_msg = {0};

    switch (sysworkmode)
    {
    case SYS_INIT:
        databuff[0] = messagedata[0];
        Ttick = xTaskGetTickCount();
        // if (xQueueReceive(send_q, &amp_send_msg, portMAX_DELAY) > 0)
        // {
        //     sysworkmode = SEND_MODE;
        // }
        sysworkmode = SEND_MODE;
        break; // 本状态下应去消息队列取数据，暂时测试未加
    case SEND_MODE:
        if (xTaskGetTickCount() - Ttick >= 1000)
        {
            Ttick = xTaskGetTickCount();
            switch (cmdworkmode)
            {
            case CMD_INFORM:
                databuff[0] = 0x12;
                break;
            case CMD_REQ:
                databuff[0] = 0x34;
                break;
            case CMD_ANS:
                databuff[0] = 0x56;
                break;
            }
            databuff[1] = num;
            databuff[2] = messagedata[2];
            for (i = 3; i < 50; i++)
            {
                databuff[i] = TESTDATA[i - 3];
            }

            if (databuff[2] == 29)
                inlen = strlen((char *)&(databuff[3])) + 3;
            else
                inlen = codelen[databuff[2]] + 3;
            base64_encode((char *)databuff, inlen, senddata, &sendlen);
            VIRT_UART_Transmit(&huart0, (unsigned char *)senddata, sendlen);
            osDelay(1);
        }
        if (RECIVE_ACK == 1)
        {
            RECIVE_ACK = 0;
            Ttick = xTaskGetTickCount();
            num++;
            if (num >= 255)
                num = 0;
            sysworkmode = SYS_INIT;
        }
        if ((xTaskGetTickCount() - Ttick >= 3000) && (RECIVE_ACK == 0))
        {
            Ttick = xTaskGetTickCount();
            sysworkmode = RESEND_MODE;
        }
        osDelay(10);
        break;
    case RESEND_MODE:
        if (sendcount < 3)
        {
            int sendlen;
            int inlen;
            inlen = codelen[databuff[2]];
            base64_encode((char *)databuff, inlen, senddata, &sendlen);
            VIRT_UART_Transmit(&huart0, (unsigned char *)senddata, sendlen);
            osDelay(10);
            sendcount++;
            if (RECIVE_ACK == 1)
            {
                RECIVE_ACK = 0;
                sendcount = 0;
                sysworkmode = SYS_INIT;
                num++;
            }
        }
        else
        {
            sendcount = 0;
            sysworkmode = SYS_INIT;
            num++;
        }

        break;
    }
}

/**
 * @brief M4接收A7核间通讯的信息
 */
void receivmesg(void)
{
    char indata[20] = {0};
    int inlen;
    char senddata[5];
    int sendlen, i;
    uint8_t ACKBUFF[2];
    base64_decode((char *)Copy_Buffer, RxSize, indata, &inlen);
    for (i = 0; i < inlen; i++)
    {
        Revdata[i] = indata[i];
    }
    if (Revdata[0] == 0xAA)
    {
        RECIVE_ACK = 1;
        memset(Copy_Buffer, 0, RxSize);
    }
    else if (Revdata[0] == 0x12)
    {
        if (Revdata[2] == 0x05)
        {
            uint16_t charge_ctrl = Revdata[3];
            log_d("recv app start %d", charge_ctrl);
            general_cmd_map_set(CMD_MAP_CHARGE, CHARGE_CTRL, (uint8_t *)&charge_ctrl, 2u);
        }
    }
    else
    {
        ACKBUFF[0] = 0xAA;
        ACKBUFF[1] = indata[1];
        ACKFLAG = 1;
        Ttickack = xTaskGetTickCount();
        base64_encode((char *)ACKBUFF, 2, senddata, &sendlen);
        VIRT_UART_Transmit(&huart0, (unsigned char *)senddata, sendlen);
        memset(Copy_Buffer, 0, RxSize);
    }
}

void VIRT_UART0_RxCpltCallback(VIRT_UART_HandleTypeDef *huart)
{
    /* M4 copies the received data to the receiving buffer of the  Virtual UART0 */
    RxSize = huart->RxXferSize < MAX_BUFFER_SIZE ? huart->RxXferSize : MAX_BUFFER_SIZE - 1;
    /* M4 copies the received data from the receiving buffer to the VirtUart0ChannelBuffRx */
    memcpy(Copy_Buffer, huart->pRxBuffPtr, RxSize);
    log_d("viri recv data.");
    flag = SET;
}

int Viri_send(uint8_t cmd, uint8_t index)
{
    int ret = 0;
    amp_send_msg_t amp_send_msg = {0};

    amp_send_msg.cmd_fun = cmd;
    amp_send_msg.index = index;
    amp_send_msg.num++;
    ret = xQueueSend(send_q, &amp_send_msg, 0u);
    return ret;
}